package com.sx.pipeline.ui.needs.supplier.detail

import android.annotation.SuppressLint
import android.text.TextUtils
import android.util.Log
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.lxj.xpopup.XPopup
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.custom.dialog.DialogPasswordInput
import com.sx.pipeline.databinding.ActSupplierNeedsDetailBinding
import com.sx.pipeline.ui.needs.construction.participation.ParticipationNeedsVM
import com.sx.pipeline.utils.AndroidUtil
import com.sx.pipeline.utils.CountDownUtil


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 供应商  需求详情
 */
@Route(path = RoutePath.Mine.SUPPLIER_NEEDS_DETAIL)
class SupplierNeedsDetailActivity :
    CYDataBindingBaseActivity<ActSupplierNeedsDetailBinding, ParticipationNeedsVM>(R.layout.act_supplier_needs_detail),
    View.OnClickListener {
    @JvmField
    @Autowired(name = IntentKey.ID)
    var needsId: Int? = 0

    private var countDownUtil: CountDownUtil? = null //供应倒计时工具类

    override fun initData() {
        super.initData()
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }
        //请求需求详情数据
        needsId?.let { mViewModel.getNeedOrderDetail(it) }
        //获取询价价格
        mViewModel.getNeedQuote()
    }


    override fun initViewObservable() {
        super.initViewObservable()
        observe(mViewModel.needOrderDetailEvent) {
            //标题
            mBinding.tvName.text = it?.title
            //供应数量
            mBinding.tvProvideNum.text = "数量：" + it?.omsNeedServe?.quantity + it?.omsNeedServe?.unit
            //供应时间
            mBinding.tvProvideTime.text = "时间：" + it?.omsNeedServe?.startDate + "-" + it?.omsNeedServe?.endDate
            //供应服务区域
            mBinding.tvProvideArea.text = "需求服务地点：" + it?.addressDetail
            //供应负责人
            mBinding.tvProvidePrincipal.text = "需求负责人：" + it?.contact

            //发布时间
            mBinding.tvCreateTime.text = "发布时间：" + it?.createTime

            mBinding.tvCountDown.text = it?.createTime

            val endtime = AndroidUtil.date2TimeStamp(it?.expiration, "yyyy-MM-dd HH:mm")

            //初始化供应任务定时
//            endtime?.toLong()?.let { it1 -> initTimer(it1) }

            //是否已经询价 已询价展示 询价设备信息和询价信息 / 添加询价
            if (it?.orderQuotedPrice == null) {
                //显示添加询价
                mBinding.tabAddInsurance.visibility = View.VISIBLE
                mBinding.tvSubmit.text = getString(R.string.txt_add_insurance)
                //负责人联系电话
                mBinding.tvProvideContact.text = "联系方式：**** **** ****"
            } else {
                //显示 设备信息和我的询价信息
                //设备信息
//                Glide.with(this).load(it?.pmsEquipment.productImage).into(mBinding.ivDeviceImg)
//                mBinding.tvDeviceName.text = it?.pmsEquipment.name
//                mBinding.tvDeviceModel.text = "产品型号：" + it?.pmsEquipment.productModel
//                mBinding.tvDeviceFactoryTime.text = "出厂日期：" + it?.pmsEquipment.productionDate

                //询价信息
                mBinding.tvPrice.text = "单价：${it?.orderQuotedPrice.price}元  总价：${it?.orderQuotedPrice.totalPrice}元"
                mBinding.tvNeedTime.text =
                    "供货时间：" + it?.orderQuotedPrice.startTime + "-" + it?.orderQuotedPrice.endEnd
                //负责人联系电话
                mBinding.tvProvideContact.text = "联系方式：" + it?.contactPhone
                mBinding.tabMyInsurance.visibility = View.VISIBLE
                mBinding.tvSubmit.text = getString(R.string.txt_dial_number)
            }
        }

        observe(mViewModel.needPriceEvent){
            if (it!!.toInt()!=0){
                //价格
                mBinding.tvProvideMoney.text=it.toString()
                mBinding.tvProvideMoney.visibility=View.VISIBLE
            }

        }
    }

//    private fun initTimer(endtime: Long) {
//        if (countDownUtil == null) {
//            countDownUtil = CountDownUtil()
//        }
//        Log.d("fsdf", "" + endtime)
//        //倒计时
//        countDownUtil!!.start((endtime!! * 1000), object :
//            CountDownUtil.OnCountDownCallBack {
//            @SuppressLint("SetTextI18n")
//            override fun onProcess(
//                day: String,
//                hour: String,
//                minute: String,
//                second: String
//            ) {
//                mBinding.tvCountDown.text = day + "天" + hour + ":" + minute + ":" + second
//            }
//
//            override fun onFinish() {}
//        })
//    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_use_time -> {
                CardDatePickerDialog.builder(this)
                    .setTouchHideable(true)
                    .showBackNow(false)
                    .setMinTime(System.currentTimeMillis())
                    .showFocusDateInfo(false)
                    .setWrapSelectorWheel(false)
                    .setTitle("选择开始时间")
                    .showDateLabel(true)
                    .setBackGroundModel(CardDatePickerDialog.STACK)
                    .setDisplayType(
                        DateTimeConfig.YEAR,
                        DateTimeConfig.MONTH,
                        DateTimeConfig.DAY,
                        DateTimeConfig.HOUR,
                        DateTimeConfig.MIN
                    )
                    .setLabelText("年", "月")
                    .setOnChoose("选择") {
                        mBinding.tvUseTime.text =
                            AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                    }
                    .setOnCancel("关闭") {

                    }
                    .build().show()
            }
            R.id.tv_end_time -> {
                CardDatePickerDialog.builder(this)
                    .setTouchHideable(true)
                    .showBackNow(false)
                    .setMinTime(System.currentTimeMillis())
                    .showFocusDateInfo(false)
                    .setWrapSelectorWheel(false)
                    .setTitle("选择结束时间")
                    .showDateLabel(true)
                    .setBackGroundModel(CardDatePickerDialog.STACK)
                    .setDisplayType(
                        DateTimeConfig.YEAR,
                        DateTimeConfig.MONTH,
                        DateTimeConfig.DAY,
                        DateTimeConfig.HOUR,
                        DateTimeConfig.MIN
                    )
                    .setLabelText("年", "月")
                    .setOnChoose("选择") {
                        mBinding.tvEndTime.text =
                            AndroidUtil.conversionTime(it, "yyyy-MM-dd HH:mm")
                    }
                    .setOnCancel("关闭") {

                    }
                    .build().show()
            }
            //查看设备详情
            R.id.tab_device_info -> {
//                mViewModel.supplyDetailEvent.value?.equipmentId?.let {
//                    RouteManager.Mine.intentToDeviceDetail(
//                        it, true
//                    )
//                }
            }
            //添加询价
            R.id.tv_submit -> {
                if (mViewModel.needOrderDetailEvent.value?.orderQuotedPrice == null) {
                    if (TextUtils.isEmpty(mBinding.etUnitPrice.text.toString())){
                        ToastUtils.showShort("请填写单价")
                        return
                    }
                    if (TextUtils.isEmpty(mBinding.etTotalPrice.text.toString())){
                        ToastUtils.showShort("请填写总价")
                        return
                    }
                    if (TextUtils.isEmpty(mBinding.tvUseTime.text.toString())){
                        ToastUtils.showShort("请选择供货开始时间")
                        return
                    }
                    if (TextUtils.isEmpty(mBinding.tvEndTime.text.toString())){
                        ToastUtils.showShort("请选择供货结束时间")
                        return
                    }
                    if (mViewModel.needPriceEvent.value?.toInt()==0){
                        //添加询价
                        needsId?.let {
                            mViewModel.addQuotedPrice(
                                it,
                                mBinding.etUnitPrice.text.toString(),
                                mBinding.etTotalPrice.text.toString(),
                                mBinding.tvUseTime.text.toString(),
                                mBinding.tvEndTime.text.toString(),
                                ""
                            )
                        }
                    }else{
                        val popup =
                            DialogPasswordInput(this, mViewModel.needPriceEvent.value.toString()).setPassInputListener { pass ->
                                //添加询价
                                needsId?.let {
                                    mViewModel.addQuotedPrice(
                                        it,
                                        mBinding.etUnitPrice.text.toString(),
                                        mBinding.etTotalPrice.text.toString(),
                                        mBinding.tvUseTime.text.toString(),
                                        mBinding.tvEndTime.text.toString(),
                                        pass
                                    )
                                }
                            }
                        XPopup.Builder(this)
                            .borderRadius(42f)
                            .isDarkTheme(false)
                            .asCustom(popup)
                            .show()
                    }

                } else {
                    //拨打电话
                    XPopup.Builder(this)
                        .isDestroyOnDismiss(true)
                        .asConfirm(
                            getString(R.string.txt_please_confirm_mobile_number), mViewModel.needOrderDetailEvent.value?.contactPhone+"该号码将被加密保护",
                            getString(R.string.cancel), getString(R.string.txt_dial_number),
                            {
                                mViewModel.needOrderDetailEvent.value?.contactPhone?.let {
                                    AndroidUtil.toCallPhone(
                                        it,this)
                                }
                            }, null, false
                        ).show()
                }

            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //销毁定时器
        countDownUtil?.onDestroy()
    }

}